<?php
/**
 * Created by PhpStorm.
 * User: xh
 * Date: 2019/11/22
 * Time: 4:28 PM
 */

namespace weChat;


use weChat\model\WeChatGlobalToken;
use weChat\pay\Pay;
use weChat\pay\Refund;
use weChat\pay\Notify;
use weChat\pay\RefundQuery;
use weChat\pay\OrderQuery;
use weChat\pay\Remit;
use weChat\pay\Transfers;
use weChat\model\WeChatAccount;
use weChat\pay\UniformMessage;

class Serve
{
    /**
     * 获取全局 AccessToken
     * 1.codeUnLimit 本类
     * @param $accessToken
     * @param $identity
     * @return bool
     */
    public function globalAccessToken(&$accessToken, $identity = 'A')
    {
        $GlobalToken = new WeChatGlobalToken();
        $res = $GlobalToken->info($accessToken,$identity);
        if($res){return true;}
        $appId = '';
        $appSecret = '';
        $WeChatAccount = new WeChatAccount();
        $WeChatAccount->info($identity, $appId, $appSecret);
        Applied::$AppId = $appId;
        Applied::$AppSecret = $appSecret;
        $info = Applied::GlobalAccessToken();
        if (empty($info)) {
            return false;
        }
        $arr = JsonDe($info);
        $accessToken = $arr['access_token'];
        $GlobalToken->add($arr['access_token'],$arr['expires_in'],$identity);
        return true;
    }

    /**
     * 生产小程序码
     * 1.model-weChat-WeChatCode-reg
     * @param $scene
     * @param $page
     * @param string $identity
     * @return bool|mixed
     */
    public function codeUnLimit($scene, $page, $identity = 'A')
    {
        $accessToken = '';
        if (!$this->globalAccessToken($accessToken, $identity)) {
            return false;
        }
        return Applied::CodeUnLimit($accessToken, $scene, $page);
    }

    /**
     * 使用code 换取 sessionKey
     * 1.plat-manage-WeChat-auth 调用
     * @param $authCode
     * @param string $sessionKey
     * @param string $openid
     * @param array $error
     * @param string $identity
     * @return bool
     */
    public function sessionKey($authCode, &$sessionKey = '', &$openid = '', &$error=[], $identity = 'A')
    {
        $appId = '';
        $appSecret = '';
        $WeChatAccount = new WeChatAccount();
        $WeChatAccount->info($identity, $appId, $appSecret);
        Applied::$AppId = $appId;
        Applied::$AppSecret = $appSecret;
        $keyRes = Applied::SessionKey($authCode);
        if (!$keyRes) {
            return false;
        }
        $keyArr = JsonDe($keyRes);
        if (isset($keyArr['errcode'])) {
            addLog($keyRes,'wechat');
            $error = $keyArr;
            return false;
        }
        $openid = $keyArr['openid'];
        $sessionKey = $keyArr['session_key'];
        return true;
    }

    /**
     * 解密微信数据
     * 1.plat-manage-WeChat-auth 调用
     * @param string $userInfo
     * @param string $SessionKey
     * @param string $Iv
     * @param string $EncryptedData
     * @param string $identity
     * @return int
     */
    public function userInfo(&$userInfo = '', $SessionKey = '', $Iv = '', $EncryptedData = '', $identity = 'A')
    {
        $appId = '';
        $appSecret = '';
        $WeChatAccount = new WeChatAccount();
        $WeChatAccount->info($identity, $appId, $appSecret);
        Applied::$AppId = $appId;
        Applied::$AppSecret = $appSecret;
        return Applied::UserInfo($SessionKey, $Iv, $EncryptedData, $userInfo);
    }

    /**
     * 解密微信数据 手机
     * @param $phoneInfo
     * @param string $SessionKey
     * @param string $Iv
     * @param string $EncryptedData
     * @param string $identity
     * @return int
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function phoneInfo(&$phoneInfo,$SessionKey = '', $Iv = '', $EncryptedData = '',$identity = 'A'){
        $appId = '';
        $appSecret = '';
        $WeChatAccount = new WeChatAccount();
        $WeChatAccount->info($identity, $appId, $appSecret);
        Applied::$AppId = $appId;
        Applied::$AppSecret = $appSecret;
        return Applied::UserInfo($SessionKey, $Iv, $EncryptedData, $phoneInfo);
    }

//    支付类型 start

    /**
     * 调起支付
     * 1.plat-login-Cost-pay 会员开通费用
     * 1.model-item-ItemOrder-make 产品支付
     * @param string $outTradeNo 订单号
     * @param string $totalFee 交易金额
     * @param string $notifyUrl 回调地址
     * @param string $body 描述
     * @param string $openid 身份标识
     * @param string $identity 身份类型
     * @param string $tradeType 支付方式
//     * @return array
     */
    public function pay(string $outTradeNo, string $totalFee, string $notifyUrl, string $body = '未知', string $openid = '', string $identity = 'A', string $tradeType = 'JSAPI')
    {
        $appId = '';
        $appSecret = '';
        $mchId = '';
        $key = '';
        $WeChatAccount = new WeChatAccount();
        $res = $WeChatAccount->info($identity, $appId, $appSecret, $mchId, $key);
        if(!$res){
            return 45001;
        }

        $pay = new Pay();
        $pay->appId = $appId;
        $pay->secret = $appSecret;
        $pay->mchId = $mchId;
        $pay->key = $key;
        $pay->body = $body;
        $pay->outTradeNo = $outTradeNo;
        $pay->totalFee = $totalFee;
        $pay->tradeType = $tradeType;
        if ($tradeType == 'JSAPI') {
            $pay->openid = $openid;
        }
        $pay->notifyUrl = $notifyUrl;
        $payInfo = [];
        $pay->handle($payInfo);
        return $payInfo;
    }

    /**
     * 支付回调
     * 1.pit-notify-Handle-entranced 调用
     * @param array $notifyInfo 微信返回数据数组
     * @param string $returnString 通知微信xml信息
     * @param string $identity 身份类型
     * @return bool
     */
    public function notify(array &$notifyInfo, string &$returnString, string $identity = 'A')
    {
        $appId = '';
        $appSecret = '';
        $mchId = '';
        $key = '';
        $WeChatAccount = new WeChatAccount();
        $WeChatAccount->info($identity, $appId, $appSecret, $mchId, $key);
        $notify = new Notify();
        $notify->appId = $appId;
        $notify->secret = $appSecret;
        $notify->mchId = $mchId;
        $notify->key = $key;
        $notifyInfo = [];
        $returnString = '';
        return $notify->handle($notifyInfo, $returnString);
    }

    /**
     * 退款
     * @param string $outTradeNo 订单号
     * @param string $outRefundNo 退款订单号
     * @param string $totalFee 总金额
     * @param string $refundFee 退款金额
     * @param string $identity 身份类型
     * @param string $refundDesc 退款说明
     * @return array
     */
    public function refund(string $outTradeNo, string $outRefundNo, string $totalFee, string $refundFee, string $identity = 'A', string $refundDesc = ''): array
    {
        $appId = '';
        $appSecret = '';
        $mchId = '';
        $key = '';
        $cert = '';
        $WeChatAccount = new WeChatAccount();
        $WeChatAccount->info($identity, $appId, $appSecret, $mchId, $key,$cert);
        $refund = new Refund();
        $refund->appId = $appId;
        $refund->secret = $appSecret;
        $refund->mchId = $mchId;
        $refund->key = $key;
        $refund->outTradeNo = $outTradeNo;
        $refund->outRefundNo = $outRefundNo;
        $refund->totalFee = $totalFee;
        $refund->refundFee = $refundFee;
        $refund->refundDesc = $refundDesc;
        $refundInfo = [];
        $refund->handle($refundInfo,$cert);
        return $refundInfo;
    }

    /**
     * 打款
     * @param string $partner_trade_no 打款单号
     * @param string $openid 用户openid
     * @param string $amount 打款金额
     * @param string $desc 描述
     * @param string $identity 身份类型
     * @return array
     */
    public function remit(string $partner_trade_no, string $openid, string $amount, string $desc, string $identity = 'A'): array
    {
        $appId = '';
        $appSecret = '';
        $mchId = '';
        $key = '';
        $cert = '';
        $WeChatAccount = new WeChatAccount();
        $WeChatAccount->info($identity, $appId, $appSecret, $mchId, $key,$cert);
        $remit = new Remit();
        $remit->appId = $appId;
        $remit->secret = $appSecret;
        $remit->mchId = $mchId;
        $remit->key = $key;
        $remit->partner_trade_no = $partner_trade_no;
        $remit->openid = $openid;
        $remit->amount = $amount;
        $remit->desc = $desc;
        $refundInfo = [];
        $remit->handle($refundInfo,$cert);
        return $refundInfo;
    }


    /**
     * 退款订单查询
     * @param string $outTradeNo 订单号
     * @param string $identity
     * @return array
     */
    public function refundQuery(string $outTradeNo, string $identity = 'A'): array
    {
        $appId = '';
        $appSecret = '';
        $mchId = '';
        $key = '';
        $WeChatAccount = new WeChatAccount();
        $WeChatAccount->info($identity, $appId, $appSecret, $mchId, $key);
        $refundQuery = new RefundQuery();
        $refundQuery->appId = $appId;
        $refundQuery->secret = $appSecret;
        $refundQuery->mchId = $mchId;
        $refundQuery->key = $key;
        $refundQuery->outTradeNo = $outTradeNo;
        $queryInfo = [];
        $refundQuery->handle($queryInfo);
        return $queryInfo;
    }

    /**
     * 订单查询
     * @param string $outTradeNo
     * @param string $identity
     * @return array
     */
    public function orderQuery(string $outTradeNo, string $identity = 'A'): array
    {
        $appId = '';
        $appSecret = '';
        $mchId = '';
        $key = '';
        $WeChatAccount = new WeChatAccount();
        $WeChatAccount->info($identity, $appId, $appSecret, $mchId, $key);
        $orderQuery = new OrderQuery();
        $orderQuery->appId = $appId;
        $orderQuery->secret = $appSecret;
        $orderQuery->mchId = $mchId;
        $orderQuery->key = $key;
        $orderQuery->outTradeNo = $outTradeNo;
        $queryInfo = [];
        $orderQuery->handle($queryInfo);
        return $queryInfo;
    }
//    支付类型 end

    /**
     * 发送公众号消息
     * @param string $template_id 消息模版ID
     * @param string $url 公众号模板消息所要跳转的url
     * @param string $openid 接收用户openid(公众号或小程序的都可以)
     * @param array $miniprogram 公众号模板消息所要跳转的小程序
     * @param array $data 消息数据
     */
    public function uniformMessage(string $template_id, string $url, string $openid, array $miniprogram, array $data, string $mp_identity = 'B', string $mini_identity = 'A')
    {
        if (!$this->globalAccessToken($accessToken, $mini_identity)) {
            return false;
        }
        $WeChatAccount = new WeChatAccount();
        $WeChatAccount->info($mp_identity, $mp_appid);
        $WeChatAccount->info($mini_identity, $mini_appid);
        $UniformMessage = new UniformMessage();
        $UniformMessage->accessToken = $accessToken;
        $UniformMessage->openid = $openid;
        $UniformMessage->mp_appid = $mp_appid;
        $UniformMessage->mini_appid = $mini_appid;
        $UniformMessage->template_id = $template_id;
        $UniformMessage->url = $url;
        $UniformMessage->miniprogram = $miniprogram;
        $UniformMessage->data = $data;
        return $UniformMessage->handle($accessToken);
    }

//    直播
    /**
     * 列表
     * @param array $list
     * @param int $start
     * @param int $limit
     * @param string $identity
     * @return bool|mixed
     */
    public function liveList(array &$list,$start=0,$limit=10, $identity = 'A')
    {
//        $arr = array (
//            'errcode' => 0,
//            'errmsg' => 'ok',
//            'room_info' =>
//                array (
//                    0 =>
//                        array (
//                            'name' => '测试的直播间',
//                            'cover_img' => 'http://mmbiz.qpic.cn/sz_mmbiz_png/iclQvBdTP6YryguwFk9HT4JtXto0wYJJAwfa5t30ic6tNgbo4JC72ico1LGow7Uq0QawOpiaHgSWmcdPyPL1Z930Rw/0',
//                            'start_time' => 1585976400,
//                            'end_time' => 1585994400,
//                            'anchor_name' => '胖石',
//                            'roomid' => 2,
//                            'goods' =>
//                                array (
//                                ),
//                            'live_status' => 107,
//                            'share_img' => 'http://mmbiz.qpic.cn/sz_mmbiz_png/iclQvBdTP6YryguwFk9HT4JtXto0wYJJAiacoNoLcriaBcic6dL3sJ9meLHJRC9rbrFNZHKlGWFyTHOIf67ubeWf4Q/0',
//                        ),
//                    1 =>
//                        array (
//                            'name' => '测试1111',
//                            'cover_img' => 'http://mmbiz.qpic.cn/sz_mmbiz_jpg/iclQvBdTP6YoE3ialV0YsaXKRev5HRvILGsXQ18T4Jichdxz9azzSe52CDk2xjWgtoF74rM9nHU4qEqg3uw9nhGVQ/0',
//                            'start_time' => 1585291753,
//                            'end_time' => 1585292901,
//                            'anchor_name' => '京津冀年',
//                            'roomid' => 1,
//                            'goods' =>
//                                array (
//                                ),
//                            'live_status' => 103,
//                            'share_img' => 'http://mmbiz.qpic.cn/sz_mmbiz_jpg/iclQvBdTP6YoE3ialV0YsaXKRev5HRvILGMhrRjHqeeUzlpadyhMyrUupJQRtdARCcJBwOj1dbYKCVPC5OLnoblg/0',
//                        ),
//                ),
//            'total' => 2,
//            'live_replay' =>
//                array (
//                ),
//        );
//        $list = $arr['room_info'];
//        return true;
        $accessToken = '';
        if (!$this->globalAccessToken($accessToken, $identity)) {
            return false;
        }
        $res = Live::list($accessToken, $start, $limit);
        if (empty($res)) {
            return false;
        }
        $arr = JsonDe($res);
        if ($arr['errcode'] != 0) {
            return false;
        }
        $list = $arr['room_info'];
        return true;
    }


    public function transfers(string $openid, string $tradeNo, int $transfersFee, string $transfersDesc = '',string $identity = 'A'): array
    {
        $appId = '';
        $appSecret = '';
        $mchId = '';
        $key = '';
        $cert = '';
        $WeChatAccount = new WeChatAccount();
        $WeChatAccount->info($identity, $appId, $appSecret, $mchId, $key,$cert);
        $transfers = new Transfers();
        $transfers->appId = $appId;
        $transfers->secret = $appSecret;
        $transfers->mchId = $mchId;
        $transfers->key = $key;
        $transfers->partnerTradeNo = $tradeNo;
        $transfers->openid = $openid;
        $transfers->amount = $transfersFee;
        $transfers->desc = $transfersDesc;
        $transfersInfo = [];
        $transfers->handle($transfersInfo,$cert);
        return $transfersInfo;
        //array(9) {
        //  ["return_code"]=>
        //  string(7) "SUCCESS"
        //  ["return_msg"]=>
        //  array(0) {
        //  }
        //  ["mch_appid"]=>
        //  string(18) "wx21312ee679338466"
        //  ["mchid"]=>
        //  string(10) "1526480141"
        //  ["nonce_str"]=>
        //  string(32) "tgeWVRkA3VI2Zfnhcvzq3AOeFng0gUn2"
        //  ["result_code"]=>
        //  string(7) "SUCCESS"
        //  ["partner_trade_no"]=>
        //  string(23) "20200519175355515253283"
        //  ["payment_no"]=>
        //  string(32) "10101038781272005191775389284073"
        //  ["payment_time"]=>
        //  string(19) "2020-05-19 17:54:45"
        //}
        //array(7) {
        //  ["return_code"]=>
        //  string(7) "SUCCESS"
        //  ["return_msg"]=>
        //  string(12) "支付失败"
        //  ["mch_appid"]=>
        //  string(18) "wx21312ee679338466"
        //  ["mchid"]=>
        //  string(10) "1526480141"
        //  ["result_code"]=>
        //  string(4) "FAIL"
        //  ["err_code"]=>
        //  string(12) "AMOUNT_LIMIT"
        //  ["err_code_des"]=>
        //  string(80) "付款金额超出限制。低于最小金额1.00元或累计超过5000.00元。"
        //}
    }
}